import Vue from 'vue'
import Vuex from 'vuex'
import {login, logout, register} from '@/api/login'
import {curUserInfo} from "@/api/userInfo";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    id: '',
    account: '',
    avatar: '',
    token: localStorage.token,
  },
  mutations: {
    SET_TOKEN (state, token){
      state.token = token;
    },
    SET_ACCOUNT(state, account) {
      state.account = account
    },
    SET_AVATAR(state, avatar) {
      state.avatar = avatar
    },
    SET_ID(state, id) {
      state.id = id
    }
  },
  actions: {
    register({commit}, user) {
      //promise用来传递异步操作信息
      return new Promise((resolve, reject) => {
        register(user).then((res) => {
          if(res.data.success){
            commit('SET_TOKEN', res.data.data)
            localStorage.token = res.data.data;
            resolve()
          }else{
            reject(res.data.msg)
          }
        }).catch((error) => {
          reject(error)
        })

      })
    },
      login({commit}, user) {
      //promise用来传递异步操作信息
      return new Promise((resolve, reject) => {
        login(user).then((res) => {
          if(res.data.success){
            commit('SET_TOKEN', res.data.data)
            localStorage.token = res.data.data;
            resolve()
          }else{
            reject(res.data.msg)
          }
        }).catch((error) => {
          reject(error)
        })

      })
    },
      logout({commit}) {
      return new Promise((resolve, reject) => {
          logout().then((res) => {
          if(res.data.success){
              commit('SET_ACCOUNT','')
              commit('SET_ID', '')
              commit('SET_AVATAR','')
              commit('SET_TOKEN','')
              localStorage.removeItem("token")
              resolve()
          }else{
            reject(res.data.msg)
          }
        }).catch((error) => {
          reject(error)
        })

      })
    },
      getUserInfo({commit}) {
      return new Promise((resolve, reject) => {
        curUserInfo().then((res) => {
            // alert("h")
          if(res.data.success){
              commit('SET_ACCOUNT', res.data.data.account)
              commit('SET_ID', res.data.data.id)
              commit('SET_AVATAR', res.data.data.icon)
              resolve(res.data)
          }else{
              //获取失败时 清除变量信息
              commit('SET_ACCOUNT','')
              commit('SET_ID', '')
              commit('SET_AVATAR','')
              commit('SET_TOKEN','')
              localStorage.removeItem("token")
              reject(res.data.msg)
          }
        }).catch((error) => {
            commit('SET_ACCOUNT','')
            commit('SET_ID', '')
            commit('SET_AVATAR','')
            commit('SET_TOKEN','')
            localStorage.removeItem("token")
            reject(error)
          reject(error)
        })
      })
    }
  }
})
